import { UseSystem, useSystemAs } from '../../../src/screenplay/abilities';
import { actorCalled } from '@serenity-js/core';
import Chai from 'chai';
import Sinon from 'sinon';
import { CreateRecord } from '../../../src/screenplay/interactions';

const { expect } = Chai;

describe('CreateRecord interaction', () => {
  let salesforceApiStub: Sinon.SinonStub;
  let createStub: Sinon.SinonStub;

  before(() => {
    createStub = Sinon.stub();
    salesforceApiStub = Sinon.stub(UseSystem.prototype, 'salesforceApi');
    salesforceApiStub.returns(
      new Promise((resolve) =>
        resolve({
          create: createStub,
        })
      )
    );
  });

  it('creates correct record', async () => {
    await actorCalled('john')
      .whoCan(useSystemAs('Sales'))
      .attemptsTo(
        CreateRecord.ofType('Account').withFields({
          Name: 'TestAccount',
        })
      );
    expect(createStub).to.have.been.calledWith('Account', [
      {
        attributes: {
          type: 'Account',
        },
        Name: 'TestAccount',
      },
    ]);
  });

  it('uses provided record description', () => {
    const description = 'TestAccount record';
    const createRecordAction = CreateRecord.ofType('Account')
      .withFields({
        Name: 'TestAccount',
      })
      .describedAs(description);
    expect(createRecordAction.toString()).to.equal(`#actor creates ${description}`);
  });

  it('has a default record description', () => {
    const objectType = 'Account';
    const createRecordAction = CreateRecord.ofType(objectType);
    expect(createRecordAction.toString()).to.equal(`#actor creates ${objectType} record`);
  });

  it('has a default record description with fields', () => {
    const objectType = 'Account';
    const fields = {
      Name: 'TestAccount',
    };
    const createRecordAction = CreateRecord.ofType(objectType).withFields(fields);
    expect(createRecordAction.toString()).to.equal(
      `#actor creates ${objectType} record with fields: ${JSON.stringify(fields, null, 2)}`
    );
  });
});
